/*
 *  Copyright (C) 2011 Dan de la Cruz <ddcruzg@gmail.com>
 * 
 *  Viajero Fashion is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  Viajero Fashion is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.vfashion.controller;

import com.google.gson.Gson;
import com.vfashion.domain.Carrito;
import com.vfashion.domain.Cliente;
import com.vfashion.domain.Paquete;
import com.vfashion.model.ClienteModelo;
import com.vfashion.model.VfashionModel;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Dan de la Cruz <ddcruzg@gmail.com>
 */

public class VFcarrito extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String alias = req.getServletPath();

        System.out.println("VFcarrito : " + alias);

        if (alias.equals("/AddPkg")) {
            addPkg(req, resp);
        } else if (alias.equals("/RemovePkg")) {
            removePkg(req, resp);
        } else if (alias.equals("/BuyAll")) {
            buyAll(req, resp);
        } else if (alias.equals("/CheckOut")) {
            checkOut(req, resp);
        } else if (alias.equals("/ShowPkgs")) {
            showPkgs(req, resp);
        } else if (alias.equals("/Details")) {
            details(req, resp);
        } else if (alias.equals("/Amount")) {
            amount(req, resp);
        } else if (alias.equals("/Seller")) {
            seller(req, resp);
        } else if (alias.equals("/ListClients")) {
            listClients(req, resp);
        } else if (alias.equals("/SellerAdd")) {
            sellerAdd(req, resp);
        } else if (alias.equals("/SellerRegister")) {
            sellerRegister(req, resp);
        } else if (alias.equals("/SellerAmount")) {
            sellerAmount(req, resp);
        }

    }

    private void addPkg(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("Agregando Paquete");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        String p = (String) req.getParameter("paquete");
        String c = (String) req.getParameter("cantidad");
        System.out.println("paquete : " + p);
        System.out.println("cantidad : " + c);
        try {
            int idpaquete = (p != null) ? Integer.parseInt(p) : -1;
            int cantidad = (c != null) ? Integer.parseInt(c) : -1;
            VfashionModel mdlVfashion = new VfashionModel();
            Paquete paquete = mdlVfashion.getPaquete(idpaquete);
            if (carrito != null) {
                carrito.add(paquete, cantidad);
                session.setAttribute("CARRITO", carrito);
            } else {
                System.out.println("NO EXISTE CARRITO");
            }

        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("CheckOut");
            rd.forward(req, resp);
        }
    }

    private void removePkg(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("Quitando Paquete");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        String p = (String) req.getParameter("paquete");
        System.out.println("paquete : " + p);
        try {
            int idpaquete = (p != null) ? Integer.parseInt(p) : -1;

            if (carrito != null) {
                carrito.quitarPaquete(idpaquete);
                session.setAttribute("CARRITO", carrito);
            } else {
                System.out.println("NO EXISTE CARRITO");
            }

        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("CheckOut");
            rd.forward(req, resp);
        }
    }

    private void buyAll(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("Comprar todo");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        Cliente cliente = (Cliente) session.getAttribute("CLIENTE");
        String page = "satisfactorio.jsp";
        try {
            VfashionModel mdlVfashion = new VfashionModel();
            mdlVfashion.realizarVenta(cliente, carrito);
        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
            page = ex.getMessage().equals("session") ? "login.jsp" : "paquetes.jsp";
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher(page);
            rd.forward(req, resp);
        }
    }

    private void showPkgs(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("Mostrando Paquetes");
        HttpSession session = req.getSession(true);
        try {
            VfashionModel mdlVfashion = new VfashionModel();
            List<Paquete> lstPaquetes = mdlVfashion.listPaquetes();
            req.setAttribute("lista", lstPaquetes);
        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("paquetes.jsp");
            rd.forward(req, resp);
        }
    }

    private void checkOut(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("Agregando Paquete");
        HttpSession session = req.getSession(true);
        try {
            Carrito carrito = (Carrito) session.getAttribute("CARRITO");
            session.setAttribute("CARRITO", carrito);

        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("carrito.jsp");
            rd.forward(req, resp);
        }
    }

    private void details(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        System.out.println("Mostrando Detalle de Paquete");
        HttpSession session = req.getSession(true);
        String nropaquete = (String) req.getParameter("paquete");
        System.out.println("nropaquete : " + nropaquete);
        try {
            int idpaquete = (nropaquete != null) ? Integer.parseInt(nropaquete) : -1;
            VfashionModel mdlVfashion = new VfashionModel();
            Paquete paquete = mdlVfashion.getPaquete(idpaquete);
            System.out.println("id : " + paquete.getIdpaquete());
            System.out.println("lugar : " + paquete.getLugar());
            req.setAttribute("paquete", paquete);
        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("detalles.jsp");
            rd.forward(req, resp);
        }

    }

    private void amount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("Modificando Cantidad Paquete");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        String p = (String) req.getParameter("paquete");
        String c = (String) req.getParameter("cantidad");
        System.out.println("paquete : " + p);
        System.out.println("cantidad : " + c);
        try {
            int idpaquete = (p != null) ? Integer.parseInt(p) : -1;
            int cantidad = (c != null) ? Integer.parseInt(c) : -1;
            VfashionModel mdlVfashion = new VfashionModel();
            Paquete paquete = mdlVfashion.getPaquete(idpaquete);
            if (carrito != null) {
                carrito.cambiarCantidad(paquete, cantidad);
                session.setAttribute("CARRITO", carrito);
            } else {
                System.out.println("NO EXISTE CARRITO");
            }

        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("CheckOut");
            rd.forward(req, resp);
        }
    }

    private void seller(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("seller");
        HttpSession session = req.getSession(true);
        try {
            VfashionModel mdlVfashion = new VfashionModel();
            List<Paquete> lstPaquetes = mdlVfashion.listPaquetes();
            req.setAttribute("lista", lstPaquetes);
            Carrito carrito = (Carrito) session.getAttribute("CARRITO");
            session.setAttribute("CARRITO", carrito);
        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("vendedor.jsp");
            rd.forward(req, resp);
        }
    }

    private void listClients(HttpServletRequest req, HttpServletResponse resp) {
        resp.setContentType("application/json; charset=utf-8");
        try {
            System.out.println("Listando Clientes");
            String term = req.getParameter("term");
            System.out.println("term : " + term);
            ClienteModelo mdlCliente = new ClienteModelo();
            List<HashMap> clientes = mdlCliente.getLike(term);
            Gson gson = new Gson();
            PrintWriter out = resp.getWriter();
            out.println(gson.toJson(clientes));

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void sellerAdd(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("Agregando Paquete");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        String p = (String) req.getParameter("paquete");
        String c = (String) req.getParameter("cantidad");
        String idcli = (String) req.getParameter("id_cliente");
        System.out.println("paquete : " + p);
        System.out.println("cantidad : " + c);
        System.out.println("id_cliente : " + idcli);
        try {
            int idpaquete = (p != null) ? Integer.parseInt(p) : -1;
            int cantidad = (c != null) ? Integer.parseInt(c) : -1;
            int idcliente = (idcli != null) ? Integer.parseInt(idcli) : -1;
            VfashionModel mdlVfashion = new VfashionModel();
            Paquete paquete = mdlVfashion.getPaquete(idpaquete);
            ClienteModelo mdlCliente = new ClienteModelo();
            Cliente cli = mdlCliente.getById(idcliente);
            if (carrito != null) {
                carrito.add(paquete, cantidad);
                session.setAttribute("CARRITO", carrito);
            } else {
                System.out.println("NO EXISTE CARRITO");
            }
            session.setAttribute("nombre", (cli.getNombre() +" "+ cli.getPaterno() +" "+ cli.getMaterno()) );
            session.setAttribute("idcliente",idcli);

        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("Seller");
            rd.forward(req, resp);
        }
    }

    private void sellerRegister(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        System.out.println("Comprar todo");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        String c = (String) req.getParameter("idcliente");
        String mensaje = "";
        System.out.println("idcliente :"+c);
        int idcliente = (c != null) ? Integer.parseInt(c) : -1;
        System.out.println("idcliente :"+idcliente);

        String page = "vendedor.jsp";
        try {
            Cliente cliente = new ClienteModelo().getById(idcliente);
            VfashionModel mdlVfashion = new VfashionModel();
            mdlVfashion.realizarVenta(cliente, carrito);
            req.setAttribute("mensaje", "VENTA REALIZADA");
        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
            page = ex.getMessage().equals("session") ? "login.jsp" : "vendedor.jsp";
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher(page);
            rd.forward(req, resp);
        }
    }

    private void sellerAmount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Modificando Cantidad Paquete");
        HttpSession session = req.getSession(true);
        Carrito carrito = (Carrito) session.getAttribute("CARRITO");
        String p = (String) req.getParameter("paquete");
        String c = (String) req.getParameter("cantidad");
        System.out.println("paquete : " + p);
        System.out.println("cantidad : " + c);
        try {
            int idpaquete = (p != null) ? Integer.parseInt(p) : -1;
            int cantidad = (c != null) ? Integer.parseInt(c) : -1;
            VfashionModel mdlVfashion = new VfashionModel();
            Paquete paquete = mdlVfashion.getPaquete(idpaquete);
            if (carrito != null) {
                carrito.cambiarCantidad(paquete, cantidad);
                session.setAttribute("CARRITO", carrito);
            } else {
                System.out.println("NO EXISTE CARRITO");
            }

        } catch (Exception ex) {
            req.setAttribute("mensaje", ex.getMessage());
        } finally {
            RequestDispatcher rd = req.getRequestDispatcher("vendedor.jsp");
            rd.forward(req, resp);
        }
    }
}
